package mylittleinvestigations.CaseInformation;

import java.io.IOException;
import java.util.*;
import mylittleinvestigations.Partner;

public class PartnerManager
{
    private HashMap<String, Partner> partnerByIdHashMap;
    private Partner currentPartner;

    public PartnerManager()
    {
        this.partnerByIdHashMap = new HashMap<String, Partner>();
    }

    public void AddPartner(String id, Partner partner)
    {
        this.partnerByIdHashMap.put(id, partner);
    }

    public Partner GetPartnerFromId(String id)
    {
        return this.partnerByIdHashMap.get(id);
    }

    public Partner GetCurrentPartner()
    {
        return this.currentPartner;
    }

    public String GetCurrentPartnerId()
    {
        return this.currentPartner != null ? this.currentPartner.getId() : null;
    }

    public void SetCurrentPartner(String newPartnerId)
    {
        this.currentPartner = this.GetPartnerFromId(newPartnerId);
    }

    void SaveToXml(CaseXmlWriter writer) throws IOException
    {
        writer.StartElement("PartnerManager");
        
        writer.StartElement("PartnerByIdHashMap");
        String[] ids = this.partnerByIdHashMap.keySet().toArray(new String[0]);
        
        for (int i = 0; i < ids.length; i++)
        {
            writer.StartElement("Entry");
            String id = ids[i];
            writer.WriteTextElement("Id", id);
            this.partnerByIdHashMap.get(id).SaveToXml(writer);
            writer.EndElement();
        }
        
        writer.EndElement();
        
        writer.EndElement();
    }

    PartnerManager(CaseXmlReader reader)
    {
        this.partnerByIdHashMap = new HashMap<String, Partner>();
        
        reader.StartElement("PartnerManager");
        
        reader.StartElement("PartnerByIdHashMap");
        reader.StartList("Entry");
        
        while (reader.MoveToNextListItem())
        {
            String id = reader.ReadTextElement("Id");
            Partner partner = new Partner(reader);
            this.partnerByIdHashMap.put(id, partner);
        }
        
        reader.EndElement();
        
        reader.EndElement();
    }

    void markPartnerChildSprites() throws CaseParseException
    {
        String[] ids = this.partnerByIdHashMap.keySet().toArray(new String[0]);
        
        for (int i = 0; i < ids.length; i++)
        {
            Partner partner = this.GetPartnerFromId(ids[i]);
            partner.markChildSprites(ids[i]);
        }
    }
}